import asyncio
import cmath
import datetime
import queue
import smtplib
import threading
import time
import zlib
import sqlite3
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import requests
from aiowebsocket.converses import AioWebSocket
import json

global is_live
global roomid
global user_list
global time_limit
global count_limit
global c_list
global send_count
global limit_status
global send_temp
limit_status = False
send_count = 0
# 此处输入监听房间号
roomid = ''
# 此处输入对应主播的UID
uid = ''
send_temp = queue.Queue()
data_raw = '000000{headerLen}0010000100000007000000017b22726f6f6d6964223a{roomid}7d'
data_raw = data_raw.format(headerLen=hex(27 + len(roomid))[2:], roomid=''.join(map(lambda x: hex(ord(x))[2:], list(roomid))))
# data_raw = '000000320010000100000007000000017b22756964223a31393137363533302c22726f6f6d6964223a31313236373538307d'
# data_raw = data_raw.format()


# 可选功能：出现弹幕发送失败时发送消息至指定QQ群，需配合OPQBot
def send_QQ(Content):
    status = False  # 如需启用请改为True
    if status:
        robotqq = ""  # 机器人QQ号
        webapi = "http://127.0.0.1:8888"  # Webapi接口 http://127.0.0.1:8888
        tmp = {}
        tmp['toUser'] = 000  # QQ群号
        tmp['sendToType'] = 2
        tmp['groupid'] = 0
        tmp['content'] = Content
        tmp['atUser'] = 0
        tmp['sendMsgType'] = 'TextMsg'
        tmp1 = json.dumps(tmp)
        print(tmp1)
        result = requests.post(webapi + '/v1/LuaApiCaller?&qq=' + robotqq + '&funcname=SendMsg&timeout=10', data=tmp1)
        print(result)


def send(msg):
    global send_temp
    send_temp.put(msg)
    print("[弹幕发送] 队列新增1条弹幕！目前还有 " + str(send_temp.qsize()) + " 条弹幕未发送")
    t = threading.Thread(target=log, args=("[弹幕发送] 队列新增1条弹幕！当前队列还有 " + str(send_temp.qsize()) + " 条弹幕未发送",))
    t.start()


def send_list():
    global send_temp
    print("[程序信息] 弹幕发送队列已就绪")
    print("[弹幕发送] 当前队列还有 " + str(send_temp.qsize()) + " 条弹幕未发送")
    while True:
        try:
            data = send_temp.get(block=True)
            t = threading.Thread(target=true_send, args=(str(data),))
            t.start()
            time.sleep(2)
            print("[弹幕发送] 当前队列还有 " + str(send_temp.qsize()) + " 条弹幕未发送")
            t = threading.Thread(target=log, args=("[弹幕发送] 当前队列还有 " + str(send_temp.qsize()) + " 条弹幕未发送",))
            t.start()
        except Exception as e:
            print("\033[7;31m[程序信息] 线程出错，具体信息为 " + str(e) + "\033[0m")
            log("[程序信息] 线程出错，具体信息为 " + str(e))


def true_send(msg):
    global roomid
    global is_live
    global limit_status
    form_data = {
        'color': '16777215',
        'fontsize': '25',
        'mode': '1',
        'msg': msg,
        'rnd': '1586843292',
        'roomid': roomid,
        'csrf_token': '',  # 此处输入csrf_token
        'csrf': ''  # 此处输入csrf
    }
    # 设置cookie值帮助我们在发送弹幕的时候，服务器识别我们的身份
    cookie = {
        'Cookie': ""  # 此处输入cookie
    }
    if not is_live and not limit_status:
        # print(msg)
        res = requests.post('https://api.live.bilibili.com/msg/send', cookies=cookie, data=form_data)
        print(res.json())
        message = res.json()['message']
        if message != '':
            if message == 'csrf 校验失败' or message == '账号未登录':
                print("账号信息异常")
            else:
                clk = time.strftime("%S", time.localtime())
                print("\033[7;31m[程序信息] 弹幕发送失败，内容为 ")
                print(message, '\033[0m')
                time.sleep(3)
                send("上一条弹幕被吞，原因为：" + message + "," + clk)
            t1 = threading.Thread(target=mail, args=(msg, message,))
            t1.start()
            t2 = threading.Thread(target=send_QQ, args=("发送弹幕 " + str(msg) + " 时被吞，原因为 " + str(message),))
            t2.start()
        else:
            print("发送成功")
        # print("closed")


# 可选功能：发送弹幕失败时发送邮件至指定邮箱（默认仅支持163邮箱）
def mail(msg, message):
    status = False  # 如需启用请更改为True
    if status:
        clock = time.strftime("%H:%M:%S", time.localtime())

        fromaddr = ''  # 发件人地址
        password = ''  # 密码
        toaddrs = ['']  # 收件人地址

        content = str(clock) + " 发送弹幕失败，消息内容为： " + msg + " ，原因为： " + message
        textApart = MIMEText(content)

        m = MIMEMultipart()
        m.attach(textApart)
        m['Subject'] = '发送弹幕失败了！'
        try:
            server = smtplib.SMTP_SSL("smtp.163.com", 465)
            server.login(fromaddr, password)
            server.sendmail(fromaddr, toaddrs, m.as_string())
            server.quit()
            print('[程序信息] 已发送错误信息')
            log("[弹幕异常] 检测到机器狼发送弹幕失败，消息内容为： " + msg + " ，原因为： " + message)
        except Exception as e1:
            print(e1)


async def startup(url):
    async with AioWebSocket(url) as aws:
        converse = aws.manipulator
        await converse.send(bytes.fromhex(data_raw))
        print("[程序信息] 已进入房间，30秒后开始发送心跳包")
        tasks = [receDM(converse), sendHeartBeat(converse)]
        await asyncio.wait(tasks)


hb = '00000010001000010000000200000001'


async def sendHeartBeat(websocket):
    global send_count
    while True:
        await asyncio.sleep(30)
        await websocket.send(bytes.fromhex(hb))
        print('[程序信息] 已发送心跳包.')
        if send_count > 0:
            print("[程序信息] 检测到连接中断，开始重连")
            send_count = 0
            break
        else:
            send_count += 1


async def receDM(websocket):
    while True:
        recv_text = await websocket.receive()
        printDM(recv_text)
        # print("开始解析数据")


# 将数据包传入：
def printDM(data):
    global send_count
    global is_live
    global user_list
    # print(is_live)
    # 获取数据包的长度，版本和操作类型

    try:
        ver = int(data[6:8].hex(), 16)
        op = int(data[8:12].hex(), 16)

        # 有的时候可能会两个数据包连在一起发过来，所以利用前面的数据包长度判断，
        # if len(data) > packetLen:
        #     printDM(data[packetLen:])
        #     data = data[:packetLen]

        # 有时会发送过来 zlib 压缩的数据包，这个时候要去解压。
        if ver == 2:
            data = data[16:]
            d = zlib.decompress(data)
            a_packetLen = int(d[:4].hex(), 16)
            if len(d) > a_packetLen:
                offset = 0
                while offset <= len(d) - 1:
                    length = int(d[offset:offset + 4].hex(), 16)
                    d1 = d[offset:offset + length]
                    d1 = d1[16:].decode('utf-8', errors='ignore')
                    d1 = json.loads(d1)
                    offset += length
                    judge(d1)
            else:
                d = d[16:].decode('utf-8', errors='ignore')
                d = json.loads(d)
                t1 = threading.Thread(target=judge, args=(d,))
                t1.start()
            return

        # ver 为1的时候为进入房间后或心跳包服务器的回应。op 为3的时候为房间的人气值。
        if ver == 1:
            if op == 3:
                send_count = 0
                print('[人气值]  {}'.format(int(data[16:].hex(), 16)))
            return

        # ver 不为2也不为1目前就只能是0了，也就是普通的 json 数据。
        # op 为5意味着这是通知消息，cmd 基本就那几个了。
        if op == 5:
            try:
                jd = json.loads(data[16:].decode('utf-8', errors='ignore'))
                t1 = threading.Thread(target=judge, args=(jd,))
                # print(jd)
                t1.start()
            except Exception as e:
                print(e)
                pass
    except Exception as e:
        print(e)
        pass


def judge(jd):
    global is_live
    global user_list
    global time_limit
    global count_limit
    global limit_status
    admin = ''  # 管理员UID，用于启用和关闭弹幕发送
    order = ["#签到", "#查询", "#龙王", "#粉丝", "#数量", "#about", "#存活确认", "#帮助", "#摸头", "#许愿", "#关闭弹幕发送", "#启用弹幕发送"]
    black_list = ['544191873']
    try:
        # print(jd)
        if 'DANMU_MSG' in jd['cmd']:
            status = 1
            print('\033[7;37m[收到弹幕] ', jd['info'][2][0], ' ', jd['info'][2][1], ' ', jd['info'][1], '\033[0m')
            log("[收到弹幕] " + str(jd['info'][2][0]) + " " + str(jd['info'][2][1]) + " " + str(jd['info'][1]))
            t1 = threading.Thread(target=sql_danmu,
                                  args=(str(jd['info'][2][0]), str(jd['info'][2][1]), str(jd['info'][1]),))
            t1.start()
            # print(jd)
            clock = time.strftime("%Y-%m-%d-%H:%M", time.localtime())
            if jd['info'][1] in order and str(jd['info'][2][0]) not in black_list:
                status = user_limit_count(str(jd['info'][2][0]))
                count_limit += 1
                print(count_limit)
            if status == 0 and str(jd['info'][2][0]):
                if jd['info'][1] == "#签到":
                    t = threading.Thread(target=sign_in, args=(str(jd['info'][2][1]), str(jd['info'][2][0]),))
                    t.start()
                elif jd['info'][1] == "#查询":
                    t = threading.Thread(target=find, args=(str(jd['info'][2][1]), str(jd['info'][2][0]),))
                    t.start()
                elif jd['info'][1] == "#龙王":
                    t = threading.Thread(target=talk, args=())
                    t.start()
                elif jd['info'][1] == "#粉丝":
                    t = threading.Thread(target=fans, args=())
                    t.start()
                elif jd['info'][1] == "#数量":
                    t = threading.Thread(target=danmu_count, args=(str(jd['info'][2][0]), str(jd['info'][2][1]),))
                    t.start()
                elif jd['info'][1] == "#about":
                    t = threading.Thread(target=send, args=("机器狼V3.0.0（Python3 Ver.）",))
                    t.start()
                    t2 = threading.Thread(target=log, args=("[ABOUT] " + "这是一只机器狼，Powered by Python3",))
                    t2.start()
                elif jd['info'][1] == "#存活确认":
                    t = threading.Thread(target=send, args=("目前程序运行正常(｀・ω・´)",))
                    t.start()
                    t2 = threading.Thread(target=log, args=("[存活确认] " + "外部确认程序运行正常",))
                    t2.start()
                elif jd['info'][1] == "#帮助":
                    t = threading.Thread(target=send, args=("目前已有下列指令：#签到 #查询 #龙王 #粉丝 #数量",))
                    t.start()
                    time.sleep(1)
                    t2 = threading.Thread(target=send, args=("具体用法可看此号置顶动态，发送指令记得加上英文的#哦",))
                    t2.start()
                elif jd['info'][1] == "#帮助-签到":
                    t = threading.Thread(target=send, args=("签到就是签到呢，增加的经验值是根据等级计算的",))
                    t.start()
                elif jd['info'][1] == "#帮助-查询":
                    t = threading.Thread(target=send, args=("就是查询你的经验值和等级呢",))
                    t.start()
                elif jd['info'][1] == "#摸头" or jd['info'][1] == "#许愿":
                    t = threading.Thread(target=send, args=(str(jd['info'][2][1]) + "许.愿.成功（大概）",))
                    t.start()
                    t2 = threading.Thread(target=log, args=("[摸头提醒] " + "被摸头了！毛-1",))
                    t2.start()
                elif jd['info'][1] == "#关闭弹幕发送" and str(jd['info'][2][0]) == admin:
                    t = threading.Thread(target=send, args=("已关闭弹幕发送，重新启用前不会发送弹幕",))
                    t.start()
                    is_live = True
                elif jd['info'][1] == "#启用弹幕发送" and str(jd['info'][2][0]) == admin:
                    is_live = False
                    t = threading.Thread(target=send, args=("已启用弹幕发送",))
                    t.start()
            elif count_limit >= 30:
                if time_limit != clock:
                    count_limit = 0
                    time_limit = clock
                    limit_status = False
                elif not limit_status:
                    time.sleep(2)
                    send("已经到上限了呢，请一分钟后再试")
                    limit_status = True

        elif jd['cmd'] == 'SEND_GIFT':
            print('\033[7;36m[收到礼物] ', jd['data']['uid'], ' ', jd['data']['uname'], ' ', jd['data']['action'], ' ',
                  jd['data']['num'], 'x',
                  jd['data']['giftName'], '\033[0m')
            log("[收到礼物] " + str(jd['data']['uid']) + " " + str(jd['data']['uname']) + " " + str(
                jd['data']['action']) + " " + str(jd['data']['num']) + "x" + str(jd['data']['giftName']))
            t1 = threading.Thread(target=gift, args=(
            str(jd['data']['uid']), str(jd['data']['uname']), str(jd['data']['num']), str(jd['data']['giftName']),))
            t1.start()
        elif jd['cmd'] == 'LIVE':
            print('[通知] 主播已开播!')
            is_live = True
            log("[通知] 主播已开播!")
        elif jd['cmd'] == 'PREPARING':
            print('[通知] 主播已下播!')
            is_live = False
            log("[通知] 主播已下播!")
        elif jd['cmd'] == 'ROOM_BLOCK_MSG':
            print('[禁言消息] ', jd['uid'], ' ', jd['uname'], ' 已被禁言')
            log("[禁言消息] " + str(jd['uid']) + " " + str(jd['uname']) + " 已被禁言")
            t1 = threading.Thread(target=sql_danmu, args=(str(jd['uid']), str(jd['uname']), "已被禁言",))
            t1.start()
        elif jd['cmd'] == 'NOTICE_MSG':
            print('[其他礼物] ' + str(jd['msg_common']))
            log("[其他礼物] " + str(jd['msg_common']))
        elif jd['cmd'] == 'WELCOME_GUARD':
            print('[欢迎舰长] ' + str(jd['data']['uid']) + ' ' + str(jd['data']['username']) + ' 进入直播间')
            log("[欢迎舰长] " + str(jd['data']['uid']) + " " + str(jd['data']['username']) + " 进入直播间")
        elif jd['cmd'] == 'ENTRY_EFFECT':
            print('[舰长特效] ' + str(jd['data']['copy_writing']))
        elif jd['cmd'] == 'ACTIVITY_BANNER_UPDATE_V2':
            print('[分区排名] ' + str(jd['data']['title']))
            log("[分区排名] " + str(jd['data']['title']))
        elif jd['cmd'] == 'ROOM_REAL_TIME_MESSAGE_UPDATE':
            print('[房间信息] 粉丝数：' + str(jd['data']['fans']))
            log("[房间信息] 粉丝数：" + str(jd['data']['fans']))
        elif jd['cmd'] == 'ROOM_RANK':
            print('[榜单排行] ' + str(jd['data']['rank_desc']))
            log("[榜单排行] " + str(jd['data']['rank_desc']))
        elif jd['cmd'] == 'GUARD_BUY':
            print('\033[7;34m[舰长购买] ' + str(jd['data']['username']) + ' 购买了 ' + str(jd['data']['gift_name']) + '\033[0m')
            log("[舰长购买] " + str(jd['data']['username']) + " 购买了 " + str(jd['data']['gift_name']))
            t1 = threading.Thread(target=gift, args=(
                str(jd['data']['uid']), str(jd['data']['username']), str(1), str(jd['data']['gift_name']),))
            t1.start()
        elif jd['cmd'] == 'USER_TOAST_MSG':
            print('\033[7;34m[舰长信息] ' + str(jd['data']['toast_msg']) + ',当前直播间共有 ' + str(jd['data']['target_guard_count']) + ' 个船员\033[0m')
        elif jd['cmd'] == 'GUARD_LOTTERY_START':
            print('\033[7;34m[感谢上舰] ' + str(jd['data']['lottery']['thank_text']) + '\033[0m')
        elif jd['cmd'] == 'WELCOME':
            print('[欢迎老爷] ' + str(jd['data']['uname']) + ' 进入直播间')
            log("[欢迎老爷] " + str(jd['data']['uname']) + " 进入直播间")
        elif jd['cmd'] == 'WEEK_STAR_CLOCK':
            print('[活动数据] ' + str(jd['data']['title']))
        elif jd['cmd'] == 'VOICE_JOIN_ROOM_COUNT_INFO':
            print('[连麦申请] 当前连麦队列有 ' + str(jd['data']['apply_count']) + ' 个小可爱')
        elif jd['cmd'] == 'VOICE_JOIN_LIST':
            print('[连麦申请] 当前连麦队列有 ' + str(jd['data']['apply_count']) + ' 个小可爱')
            log("[连麦申请] 当前连麦队列有 " + str(jd['data']['apply_count']) + " 个小可爱")
        elif jd['cmd'] == 'SPECIAL_GIFT':
            print('[特殊礼物] ' + str(jd['data']['39']['content']))
        elif jd['cmd'] == 'INTERACT_WORD':
            print('\033[7;32m[互动信息] ' + str(jd['data']['uid']) + ' ' + str(jd['data']['uname']) + ' 发送了心跳包（？）\033[0m')
            log("[互动信息] " + str(jd['data']['uid']) + " " + str(jd['data']['uname']) + " 发送了心跳包（？）")
            if str(jd['data']['uid']) == '5659864':
                t = threading.Thread(target=send, args=("(=・ω・=)",))
                t.start()
        elif jd['cmd'] == 'PANEL':
            print('[榜单信息] ' + str(jd['data']['note']))
        elif jd['cmd'] == 'COMBO_END' or jd['cmd'] == 'COMBO_SEND':
            print('\033[7;36m[收到礼物] ' + str(jd['data']['uid']) + ' ' + str(jd['data']['uname']) + ' ' + jd['data']['action'] + ' ' + jd['data']['gift_name'] + ' x' + str(jd['data']['combo_num']), '\033[0m')
            t1 = threading.Thread(target=gift, args=(
                str(jd['data']['uid']), str(jd['data']['uname']), str(jd['data']['combo_num']), jd['data']['gift_name'],))
            t1.start()
            log("[收到礼物] " + str(jd['data']['uid']) + " " + str(jd['data']['uname']) + " " + jd['data']['action'] + " " + jd['data']['gift_name'] + " x" + str(jd['data']['combo_num']))
        else:
            print('\033[7;31m[其他信息] ', jd['cmd'])
            log("[其他信息] " + str(jd['cmd']))
            print(jd, '\033[0m')
    except Exception as e:
        print(e)
        pass


def log(body):
    date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    with open(str(date) + "(new).txt", "a", encoding='utf-8') as f1:
        f1.write(time.strftime("[%H:%M:%S] ", time.localtime()))
        f1.write(body + "\n")
        f1.flush()
    f1.close()


def sign_in(name, uid):
    date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    yesterday = datetime.date.today() + datetime.timedelta(-1)
    con = sqlite3.connect("user.db")
    cur = con.cursor()
    msg = "默认回复"
    success = False
    if str(uid) in user_list:
        # print("用户已在数据库中")
        level = 0
        add_exp = 0
        cur.execute("SELECT * FROM user")
        for raw in cur:
            if str(raw[0]) == str(uid) and str(raw[3]) != str(date):
                days = 1
                if str(raw[3]) == str(yesterday):
                    days = int(raw[5]) + 1
                level = int(((int(raw[2]) // 100) ** (1 / 3)) // 1)
                add_exp = 100 * (level + 1)
                cur.execute("UPDATE user SET sign_in=? WHERE uid=?", (str(date), uid))
                cur.execute("UPDATE user SET exp=? WHERE uid=?", (raw[2] + add_exp, uid))
                cur.execute("UPDATE user SET total=? WHERE uid=?", (raw[4] + 1, uid))
                cur.execute("UPDATE user SET continuous=? WHERE uid=?", (days, uid))
                success = True
        if success:
            log("[签到信息] [老用户] " + str(uid) + " " + str(name) + " 已签到")
            msg = name + "签到成功！经验+" + str(add_exp)
        else:
            log("[签到信息] [老用户]" + str(uid) + " " + str(name) + " 尝试重复签到")
            msg = name + "今天已经签到！"
    else:
        cur.execute("INSERT INTO user values(?,?,?,?,?,?)", (str(uid), str(name), 1, date, 1, 1))
        msg = name + "签到成功！经验+1"
        log("[签到信息] [新用户] " + str(uid) + " " + str(name) + " 已签到")
        user_list.append(str(uid))
    if not is_live:
        t1 = threading.Thread(target=send, args=(msg,))
        t1.start()
    con.commit()
    cur.close()
    con.close()
    # print("签到")


def user_limit_count(uid):
    global c_list
    clock = time.strftime("%Y-%m-%d-%H:%M", time.localtime())
    con = sqlite3.connect("user.db")
    cur = con.cursor()
    status = False
    if str(uid) in c_list:
        # print("用户已在数据库中")
        cur.execute("SELECT * FROM count")
        for raw in cur:
            if str(raw[0]) == str(uid):
                if raw[1] >= 2:
                    if raw[2] != clock:
                        cur.execute("UPDATE count SET l_count=? WHERE uid=?", (0, uid))
                        cur.execute("UPDATE count SET last_send=? WHERE uid=?", (clock, uid))
                        con.commit()
                        return 0
                    else:
                        con.commit()
                        return 1
                else:
                    cur.execute("UPDATE count SET l_count=? WHERE uid=?", (raw[1] + 1, uid))
                    con.commit()
                    return 0
                status = True
    else:
        cur.execute("INSERT INTO count values(?,?,?)", (str(uid), 1, clock))
        c_list.append(str(uid))
        con.commit()
        return 0
    cur.close()
    con.close()
    if not status:
        return 1


def find(name, uid):
    global user_list
    # dict = {0: "偶遇奶狗", 1: "再遇奶狗", 2: "初识奶狗"}
    msg = "默认回复"
    msg1 = ""
    if str(uid) in user_list:
        con = sqlite3.connect("user.db")
        cur = con.cursor()
        cur.execute("SELECT * FROM user")
        for raw in cur:
            if str(raw[0]) == str(uid):
                level = int(((int(raw[2]) // 100) ** (1 / 3)) // 1)
                # print(level)
                log("[查询信息] uid " + str(uid) + " 查询了经验值，目前经验值为 " + str(raw[2]) + ",等级为 " + str(level))
                msg = name + "的经验值为" + str(raw[2])
                msg1 = "等级为" + str(level) + "，累计签到" + str(raw[4]) + "天，连续签到" + str(raw[5]) + "天"
                # msg1 = "等级为" + str(level) + "(" + str(dict[level]) + ")"
                # print(msg1)
    else:
        msg = "没有找到你的信息呢，发个 #签到 试试？"
    send(msg)
    time.sleep(1)
    send(msg1)


def talk():
    yesterday = datetime.date.today() + datetime.timedelta(-1)
    con = sqlite3.connect("talk.db")
    cur = con.cursor()
    cur.execute("SELECT name, m_count FROM talk WHERE t_date=?", (str(yesterday),))
    for j in cur:
        log("[龙王查询] 昨天轮播间龙王为" + str(j[0]) + "，共发送" + str(j[1]) + "条弹幕")
        send("昨天轮播间龙王为" + str(j[0]))
        time.sleep(1)
        send("共发送" + str(j[1]) + "条弹幕")


def sql_danmu(uid, name, body):
    today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    clock = time.strftime("%H:%M:%S", time.localtime())
    con = sqlite3.connect("danmu.db")
    cur = con.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS danmu(r_day TEXT,r_clock TEXT,uid TEXT,uname TEXT,info TEXT)")
    cur.execute("INSERT INTO danmu values(?,?,?,?,?)", (str(today), str(clock), str(uid), str(name), str(body)))
    con.commit()
    cur.close()
    con.close()


def fans():
    global uid
    url = 'https://api.bilibili.com/x/relation/stat?vmid=' + str(uid)
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
    }
    result = requests.get(url=url, headers=header)
    data = result.json()
    num = num_to_char(data['data']['follower'])
    log("[粉丝查询] " + "当前粉丝数： " + str(data['data']['follower']))
    # send("当前粉丝数： " + str(data['data']['follower']))
    send("当前粉丝数： " + num)
    # send("非常抱歉，该功能暂时不可用")


def gift(uid, name, g_count, g_type):
    today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    clock = time.strftime("%H:%M:%S", time.localtime())
    con = sqlite3.connect("gift.db")
    cur = con.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS gift(r_day TEXT,r_clock TEXT,uid TEXT,uname TEXT,g_count INTEGER,g_type TEXT)")
    cur.execute("INSERT INTO gift values(?,?,?,?,?,?)", (str(today), str(clock), str(uid), str(name), g_count, str(g_type)))
    con.commit()
    cur.close()
    con.close()


def danmu_count(uid, name):
    today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    con = sqlite3.connect("danmu.db")
    cur = con.cursor()
    cur.execute("SELECT COUNT(*) FROM danmu WHERE uid=? AND r_day=?", (uid, today,))
    for i in cur:
        log("[数量查询] " + str(uid) + " 今天发了" + str(i[0]) + "条弹幕")
        send(str(name) + "今天发送了" + str(i[0]) + "条弹幕！")
    cur.close()
    con.close()


def update():
    con = sqlite3.connect("user.db")
    cur = con.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS user(uid TEXT PRIMARY KEY,uname TEXT,exp INTEGER,sign_in TEXT,total INTEGER,continuous INTEGER)")
    cur.execute("CREATE TABLE IF NOT EXISTS count(uid TEXT PRIMARY KEY,l_count INTEGER,last_send TEXT)")
    n_user = cur.execute("SELECT uid FROM user")
    for i in n_user:
        user_list.append(str(i[0]))
    c_user = cur.execute("SELECT uid FROM count")
    for i in c_user:
        c_list.append(str(i[0]))
    cur.close()
    con.close()
    print('[程序信息] 用户数据更新完毕')
    log("[程序信息] 用户数据已经更新！")


def auto_update():
    print('[程序信息] 自动更新线程已创建')
    log("[程序信息] 自动更新线程已创建")
    while True:
        try:
            now_time_hour = time.strftime("%H", time.localtime())
            now_time_min = time.strftime("%M", time.localtime())
            if int(now_time_hour) == 5 and int(now_time_min) == 20:
                update()
                time.sleep(60)
            print('[程序信息] 自动更新线程运行正常')
            time.sleep(45)
        except Exception as e:
            print(e)
            time.sleep(45)


def num_to_char(num):
    num = str(num)
    new_str = ""
    num_dict = {"0": u"零", "1": u"一", "2": u"二", "3": u"三", "4": u"四", "5": u"五", "6": u"六", "7": u"七", "8": u"八", "9": u"九"}
    listnum = list(num)
    # print(listnum)
    shu = []
    for i in listnum:
        # print(num_dict[i])
        shu.append(num_dict[i])
    new_str = "".join(shu)
    # print(new_str)
    return new_str


if __name__ == '__main__':
    global is_live
    global user_list
    global c_list
    global count_limit
    global time_limit
    global uid
    time_limit = time.strftime("%H:%M", time.localtime())
    remote = 'wss://broadcastlv.chat.bilibili.com:2245/sub'
    url = 'http://api.live.bilibili.com/bili/living_v2/' + str(uid)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/80.0.3987.149 Safari/537.36 '
    }
    while True:
        try:
            user_list = []
            c_list = []
            count_limit = 0
            update()
            # print(user_list)
            html = requests.get(url)
            result = html.json()['data']
            if int(result['status']) == 1:
                is_live = True
                print("[程序信息] 目前主播正在直播")
            else:
                is_live = False
                print("[程序信息] 目前主播未在直播")
            t1 = threading.Thread(target=auto_update, args=())
            t1.start()
            t2 = threading.Thread(target=send_list, args=())
            t2.start()
            asyncio.get_event_loop().run_until_complete(startup(remote))
        except KeyboardInterrupt as exc:
            print('程序退出')
            break
